package top.yangyitao.shiro;

import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import top.yangyitao.dao.UserRepository;
import top.yangyitao.dto.UserDto;
import top.yangyitao.entity.Permission;
import top.yangyitao.entity.Role;
import top.yangyitao.entity.User;
import top.yangyitao.entityEnum.UserStatusEnum;
import top.yangyitao.service.CacheService;
import top.yangyitao.utils.Cache;

public class ShiroRealm extends AuthorizingRealm {

	Boolean cachingEnabled=true;
	
	@Autowired
	UserRepository userDao;
	
	@Autowired
	CacheService cacheService;
	
	private static final Logger LOG = LoggerFactory.getLogger(ShiroRealm.class);

	final static String SHIRO_SESSION_CACHE_PREFIX = "shiro-session";
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
 
		SimpleAuthorizationInfo authorInfo = new SimpleAuthorizationInfo();
 
        String username = (String)principalCollection.getPrimaryPrincipal();
        
        User user = userDao.findByUsername(username);
        
        Set<String> roleSet = new HashSet<>();

        Set<String>  permissionSet = new HashSet<>();

    	Role role = user.getRole();
		roleSet.add(role.getStringRole());
		for(Permission perm : role.getPermissions()) {
			permissionSet.add(perm.getStringPermission());
		}
    	
    	authorInfo.setRoles(roleSet);
    	authorInfo.setStringPermissions(permissionSet);

		return authorInfo;
	}
	
	private void updateSession(String username,Session session) {
		Cache cache = null;
		synchronized(username.intern()) {
			//锁字符串常量池引用
			if((cache = cacheService.get(SHIRO_SESSION_CACHE_PREFIX, username)) == null) {
				cache = new ShiroSessionCache();
				cache.object = session;
				cacheService.put(SHIRO_SESSION_CACHE_PREFIX, username, cache);
			}
			else {
				Session oldSession =  (Session) cache.object;
				if(oldSession.getId()!=session.getId()) {
					try {
						oldSession.setTimeout(0);
					}catch(InvalidSessionException e){
						LOG.info(oldSession.getId()+"all ready closed");
					}
				}
				cache.object = session;
			}
		}
	}
	
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {

		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		String username = token.getUsername();
		User user = userDao.findByUsername(username);
		if(user==null){throw new AuthenticationException("用户不存在");}
		if(user.getStatus()==UserStatusEnum.unActive.getType()){throw new AuthenticationException("用户未激活");}
		AuthenticationInfo authcInfo=new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(),ByteSource.Util.bytes(user.getSalt()), getName());
		super.clearCachedAuthorizationInfo(authcInfo.getPrincipals());
		Session session = SecurityUtils.getSubject().getSession();
		updateSession(username,session);
		session.setAttribute("userDto", new UserDto().convert(user));
		return authcInfo;
	}

}
